package com.wanmait.hr.filter;

import com.alibaba.druid.util.StringUtils;
import com.wanmait.hr.util.PageContext;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@WebFilter(filterName = "PageFilter")
public class PageFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {

        HttpServletRequest httpRequest = (HttpServletRequest) request;

        PageContext.setPageNum(getPageNum(httpRequest));
        PageContext.setPageSize(getPageSize(httpRequest));

        try {
            chain.doFilter(request, response);
            return;
        }
        finally {
            PageContext.removePageNum();
            PageContext.removePageSize();
        }

    }
    protected int getPageNum(HttpServletRequest request) {
        int pageNum = 1;
        try {
            String pageNums = request.getParameter("pageNum");
            if (pageNums != null && StringUtils.isNumber(pageNums)) {
                pageNum = Integer.parseInt(pageNums);
            }
            //
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        return pageNum;
    }
    protected int getPageSize(HttpServletRequest request) {
        int pageSize = 4;    // 默认每页10条记录
        try {
            String pageSizes = request.getParameter("pageSize");
            if (pageSizes != null && StringUtils.isNumber(pageSizes)) {
                pageSize = Integer.parseInt(pageSizes);
            }
            //如果没有传一般会在数据库中能够设置，从数据库取出

        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        return pageSize;
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
